package com.junzhiit.nengji.cms.config;

import java.text.SimpleDateFormat;

import javax.servlet.MultipartConfigElement;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.cms.interceptor.AccessControlAllowOriginInterceptor;
import com.junzhiit.nengji.cms.interceptor.SessionInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableAutoConfiguration
public class WebConfig extends WebMvcConfigurerAdapter {

	public static final String[] SESSION_EXCLUDE_PATHS = new String[]{
			"/error",
			"/swagger-resources/**",
			"/shop/**",
			"/industry/**",
			"/set/meal/**",
			"/wechat/config/**",
			"/logistics/**",
			"/getMobilePhoneCode",
			"/system/user/check/mobilePhone",
			"/system/user/**",
			"/user/**",
			"/advertise/type/**",
			"/retrieve/password/phone",
			"/retrieve/password/email",
			"/send/email",
			"/getPhoneCodePwd",
			"/type/**",
			"/city/**",
			"/system/user/init/power",
			"/postage/template/**",
			"/area/info",
			"/chain/**",
			"/coupons/**",
			"/test/**",
			"/intranet/**",
			"/download/**"
	};
	
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public FilterRegistrationBean characterEncodingFilter(@Value("${character.encoding}") final String characterEncoding) {
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(characterEncoding);
        characterEncodingFilter.setForceEncoding(true);

        final FilterRegistrationBean reg = new FilterRegistrationBean();
        reg.setFilter(characterEncodingFilter);
        reg.addUrlPatterns("/*");
        return reg;
    }

    // Default JSON Date Format
    @Bean
    public ObjectMapper jsonMapper() {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat(DateUtil.DATETIME_PATTERN_DEFAULT));

        return objectMapper;
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(final ConfigurableEmbeddedServletContainer container) {
                final ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/pageNotFound");
                final ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
                container.addErrorPages(error404Page, error500Page);
            }
        };
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    MultipartConfigElement multipartConfigElement(@Value("${multipart.maxFileSize}") final String multipartMaxFileSize,
            @Value("${multipart.maxRequestSize}") final String multipartMaxRequesteSize) {
        final MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(multipartMaxFileSize);
        factory.setMaxRequestSize(multipartMaxRequesteSize);
        return factory.createMultipartConfig();
    }

//    @Bean
//    public CommonsMultipartResolver multipartResolver(){
//        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
//        commonsMultipartResolver.setDefaultEncoding("utf-8");
//        commonsMultipartResolver.setMaxUploadSize(50000000);
//        return commonsMultipartResolver;
//    }
    
    @Bean
    AccessControlAllowOriginInterceptor accessControlAllowOriginInterceptor(){
    	return new AccessControlAllowOriginInterceptor();
    }
    
    public void addInterceptors(InterceptorRegistry registry){
    	registry.addInterceptor(accessControlAllowOriginInterceptor()).addPathPatterns("/**");
    	registry.addInterceptor(new SessionInterceptor()).excludePathPatterns(SESSION_EXCLUDE_PATHS);
    	super.addInterceptors(registry);
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(new String[]{"swagger-ui.html"})
        	.addResourceLocations(new String[]{"classpath:/META-INF/resources/"});
        registry.addResourceHandler(new String[]{"/webjars*"})
        	.addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"});
    }
}
